package com.cowmooed.service.impl;

import com.aliyun.oss.OSS;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cowmooed.dto.RegisterDto;
import com.cowmooed.entity.SysUser;
import com.cowmooed.exception.GlobalExceptionHandler;
import com.cowmooed.mapper.SysUserMapper;
import com.cowmooed.properties.AliyunOssProperties;
import com.cowmooed.service.SysUserService;
import com.cowmooed.utils.ImageValidationUtil;
import com.cowmooed.utils.MD5Util;
import com.cowmooed.utils.SnowflakeIdGeneratorUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.UUID;

/**
 * 用户服务实现类
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Autowired
    private final SysUserMapper sysUserMapper;

    @Autowired
    private final AliyunOssProperties aliyunOssProperties;

    private final OSS ossClient;

    @Autowired
    private final SnowflakeIdGeneratorUtil snowflakeIdGeneratorUtil;

    @Autowired
    public SysUserServiceImpl(SysUserMapper sysUserMapper,
                            AliyunOssProperties aliyunOssProperties,
                            OSS ossClient,
                            SnowflakeIdGeneratorUtil snowflakeIdGeneratorUtil) {
        this.sysUserMapper = sysUserMapper;
        this.aliyunOssProperties = aliyunOssProperties;
        this.ossClient = ossClient;
        this.snowflakeIdGeneratorUtil = snowflakeIdGeneratorUtil;
    }
    
    /**
     * 用户注册实现
     */
    @Override
    @Transactional
    public boolean register(RegisterDto registerDto) {
        // 1. 验证用户名是否已存在
        SysUser existingUser = findByUserName(registerDto.getUserName());
        if (existingUser != null) {
            throw new GlobalExceptionHandler.BusinessException("用户名已存在");
        }

        // 2. 比对密码和确认密码是否相同
        if (!registerDto.getPassword().equals(registerDto.getConfirmPassword())) {
            throw new GlobalExceptionHandler.BusinessException("两次输入的密码不一致");
        }

        // 3. 验证用户名不为空
        if (registerDto.getUserName() == null || registerDto.getUserName().trim().isEmpty()) {
            throw new GlobalExceptionHandler.BusinessException("用户名不能为空");
        }

        // 4. 对密码进行MD5加密
        String encryptedPassword = MD5Util.encrypt(registerDto.getPassword());

        // 5. 使用Builder模式创建用户对象
        SysUser sysUser = SysUser.builder()
                .userId(snowflakeIdGeneratorUtil.nextId()) // 使用雪花算法生成userId
                .userName(registerDto.getUserName())
                .password(encryptedPassword) // 使用加密后的密码
                .avatarUrl(registerDto.getAvatarUrl())
                .createTime(LocalDateTime.now())
                .updateTime(LocalDateTime.now())
                .build();

        // 6. 插入用户 - 使用MyBatis-Plus的insert方法确保所有字段都被正确插入
        return sysUserMapper.insert(sysUser) > 0;
    }
    
    /**
     * 根据用户名查询用户
     */
    @Override
    public SysUser findByUserName(String userName) {
        return sysUserMapper.selectByUserName(userName);
    }
    
    /**
     * 根据用户名和密码查询用户
     */
    @Override
    public SysUser findByUserNameAndPassword(String userName, String password) {
        return sysUserMapper.selectByUserNameAndPassword(userName, password);
    }
    
    /**
     * 上传头像到阿里云OSS
     */
    @Override
    public String uploadAvatarToOss(MultipartFile file) {
        try {
            // 验证图像文件是否符合要求
            ImageValidationUtil.validateImage(file);
            
            // 生成唯一的文件名
            String originalFilename = file.getOriginalFilename();
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            String fileName = "avatar/" + UUID.randomUUID() + suffix;
            
            // 上传文件到OSS
            ossClient.putObject(aliyunOssProperties.getBucketName(), fileName, file.getInputStream());
            
            // 构建返回的URL
            String imageUrl = "https://" + aliyunOssProperties.getBucketName() + "." + aliyunOssProperties.getEndpoint() + "/" + fileName;
            // 验证URL地址是否包含中文字符
            ImageValidationUtil.validateUrl(imageUrl);
            return imageUrl;
        } catch (IOException e) {
            throw new GlobalExceptionHandler.BusinessException("上传头像失败");
        }
    }
}